package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.Order;
import csu.web.mypetstore.service.OrderService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ViewOrderFormServlet extends HttpServlet {
    private static final String VIEWORDER = "/WEB-INF/jsp/order/viewOrder.jsp";
    private static final String SIGNONFORM = "/WEB-INF/jsp/account/signonForm.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/error.jsp";


    private Cart cart;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        cart = (Cart) session.getAttribute("cart");
        if (cart != null) {
            Order order = new Order();
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
            order.setOrderDate(dateFormat.format(date));
            Account account = (Account) session.getAttribute("account");
            order.setUsername(account.getUsername());
            order.setCardType(request.getParameter("order.cardType"));
            order.setCreditCard(request.getParameter("order.creditCard"));
            order.setExpiryDate(request.getParameter("order.expiryDate"));
            order.setBillToFirstName(request.getParameter("order.billToFirstName"));
            order.setBillToLastName(request.getParameter("order.billToLastName"));
            order.setBillAddress1(request.getParameter("order.billAddress1"));
            order.setBillAddress2(request.getParameter("order.billAddress2"));
            order.setBillCity(request.getParameter("order.billCity"));
            order.setBillState(request.getParameter("order.billState"));
            order.setBillZip(request.getParameter("order.billZip"));
            order.setBillCountry(request.getParameter("order.billCountry"));
            OrderService orderService = new OrderService();
            orderService.insertOrder(order);

            session.setAttribute("order", order);
            request.getRequestDispatcher(VIEWORDER).forward(request, response);

            // 跳转到订单页面
        }
    }
}
